﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Permissions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VWS_Monitor
{
	public partial class Main : Form
	{
		private DateTime _currentDate = new DateTime(0);
		private DateTime _restarting = new DateTime(0);

		private RFW.Weather.CurrentConditions _currentConditions = new RFW.Weather.CurrentConditions();

		public Main()
		{
			InitializeComponent();

			_currentConditions.DownloadComplete += _currentConditions_DownloadComplete;
			_currentConditions.DownloadFailed += _currentConditions_DownloadFailed;
		}

		void _currentConditions_DownloadFailed(object sender, EventArgs e)
		{
			SetStatus("Download Failed");
			CheckUpdateTime();
		}

		private void SetStatus(string status)
		{
			uiStatusLabel.Text = string.Format("{0}\r\n{1:u}", status, DateTime.UtcNow);
		}

		void _currentConditions_DownloadComplete(object sender, EventArgs e)
		{
			uiWeatherFlashLabel.Text = _currentConditions.TimeStamp.ToString("u");
			CheckUpdateTime();
		}

		private void uiTimer_Tick(object sender, EventArgs e)
		{
			SetCurrentDateTime();
			_currentConditions.Get();
		}

		private void CheckUpdateTime()
		{
			try
			{
				TimeSpan diff = _currentDate - _currentConditions.TimeStamp;
				double totalSeconds = Math.Abs(diff.TotalSeconds);

				if (totalSeconds > Properties.Settings.Default.Tolerance && _restarting.Ticks == 0)
					RestartVWS();
				else
					SetStatus(string.Format("Last updated {0:N0} second{1} ago.", totalSeconds, totalSeconds == 1.0 ? "" : "s"));

				if (_restarting.Ticks > 0)
				{
					double minutes = (_currentDate - _restarting).TotalMinutes;
					if (Math.Abs(minutes) > Properties.Settings.Default.RestartTime)
					{
						SetStatus("Restart Time Out");
						_restarting = new DateTime(0);
					}
				}
			}
			catch (Exception ex)
			{
				SetStatus(ex.Message);
			}
		}

		private void RestartVWS()
		{
			uiTimer.Enabled = false;

			try
			{
				SetStatus(string.Format("Stopping {0}", Properties.Settings.Default.ProcessName.ToUpper()));
				Application.DoEvents();

				foreach (System.Diagnostics.Process process in System.Diagnostics.Process.GetProcesses())
				{
					if (process.ProcessName.Equals(Properties.Settings.Default.ProcessName, StringComparison.CurrentCultureIgnoreCase))
					{
						process.Kill();
					}
				}

				SetStatus(string.Format("Starting {0}", Properties.Settings.Default.ProcessFullPath.ToUpper()));
				Application.DoEvents();
				
				System.Diagnostics.Process.Start(Properties.Settings.Default.ProcessFullPath);
				_restarting = DateTime.UtcNow;

				SetStatus(string.Format("Started {0}", Properties.Settings.Default.ProcessFullPath.ToUpper()));
				Application.DoEvents();
			}
			catch (Exception ex)
			{
				SetStatus(ex.Message);
			}

			uiTimer.Enabled = true;
		}

		private void Main_Shown(object sender, EventArgs e)
		{
			uiTimer_Tick(sender, e);
			uiTimer.Enabled = true;

			SetStatus("Loaded");
		}

		private void SetCurrentDateTime()
		{
			_currentDate = DateTime.UtcNow;
			uiCurrentDateTimeLabel.Text = _currentDate.ToString("u");
		}
	}
}
